package org.hhchat.leetcode.linkList;

import org.hhchat.leetcode.dataStruct.ListNode;

import java.util.Stack;

/**
 * Created this one by HMH on 2017/5/27.
 */
public class code445 {

    public static class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            Stack<Integer> stack1 = new Stack<>();
            Stack<Integer> stack2 = new Stack<>();

            while (l1 != null) {
                stack1.push(l1.val);
                l1=l1.next;
            }
            while (l2 != null) {
                stack2.push(l2.val);
                l2=l2.next;
            }

            ListNode list = new ListNode(0);
            int sum=0;
            while (!stack1.empty() || !stack2.empty()) {
                if(!stack1.empty()) sum += stack1.pop();
                if(!stack2.empty()) sum += stack2.pop();
                list.val = sum % 10;
                ListNode head = new ListNode(sum / 10);
                head.next = list;
                list = head;
                sum /= 10;
            }
            return (list.val == 0) ? list.next : list;
        }

        public void printLink(ListNode l) {
            while (l != null) {
                System.out.println(l.val);
                l = l.next;
            }
        }
    }

    public static void main(String[] args){
        Solution solution = new Solution();
        ListNode listNode = new ListNode(7);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(4);
        listNode.next.next.next = new ListNode(5);
        ListNode listNode2 = new ListNode(5);
        listNode2.next = new ListNode(6);
        listNode2.next.next = new ListNode(4);
        listNode = solution.addTwoNumbers(listNode, listNode2);
        solution.printLink(listNode);

    }
}
